<template>
  <div class="music flex-column">
    <img :src="data.img_url" :class="['image', isPlaying ? 'rotation' : '']" />
    <img :src="playStateUrl" class="player-img" @click="onPlay" />
    <img src="https://7465-test-1082be-1257701543.tcb.qcloud.la/music/音乐。@2x.png?sign=8a679e268441f7714e83b04f942085c4&t=1538310519" class="tag" />
    <p class="content">{{data.content}}</p>
  </div>
</template>

<script>
const BAM = wx.getBackgroundAudioManager()
export default {
  name: 'Music',
  data () {
    return {
      isPlaying: false
    }
  },
  props: {
    data: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  computed: {
    playStateUrl () {
      return this.isPlaying ? 'cloud://test-1082be.7465-test-1082be/music/播放中.png' : 'cloud://test-1082be.7465-test-1082be/music/暂停中.png'
    }
  },
  methods: {
    onPlay () {
      if (!this.isPlaying) { // 未播放
        this.isPlaying = true
        if (BAM.src === this.data.url) {
          BAM.play()
        } else {
          BAM.src = this.data.url
        }
        BAM.title = this.data.title
      } else { // 已经播放
        this.isPlaying = false
        BAM.pause()
      }
      this.$emit('handlePlaying', this.isPlaying)
    },
    _recoverPlaying () {
      if (BAM.paused) {
        this.isPlaying = false
        return
      }
      if (BAM.src === this.data.url && !BAM.paused) {
        this.isPlaying = true
      }
    },
    _monitorSwitch () {
      BAM.onPlay(() => {
        this._recoverPlaying()
      })
      BAM.onPause(() => {
        this._recoverPlaying()
      })
      BAM.onStop(() => {
        this._recoverPlaying()
      })
      BAM.onEnded(() => {
        this._recoverPlaying()
      })
    }
  },
  mounted () {
    this._recoverPlaying()
    this._monitorSwitch()
  }
}
</script>

<style lang="stylus" scoped>
  .music
    justify-content center
    .image
      overflow hidden
      width 422rpx
      height 422rpx
      margin-top 60rpx
      border-radius 50%
    .tag
      position relative
      bottom 160rpx
      right 310rpx
      width 44rpx
      height 127rpx
    .content
      max-width 550rpx
      font-size 36rpx
      margin-top -90rpx
    .rotation
      transform rotate(360deg)
      animation rotation 12s linear infinite
    .player-img
      position relative
      bottom 271rpx
      width 120rpx
      height 120rpx
@-webkit-keyframes rotation
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
</style>
